﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TC.Vacation.Spider.Rules;

namespace TC.Vacation.Spider.Core
{
    internal sealed class DynamicLoadPlugin
    {
        /// <summary>
        /// 插件集合--文件名为Key
        /// </summary>
        private readonly static Dictionary<string, RulesAnalyzer> plugins = new Dictionary<string, RulesAnalyzer>();
        /// <summary>
        /// The _ dynamic load plugin
        /// </summary>
        private readonly static DynamicLoadPlugin _DynamicLoadPlugin = new DynamicLoadPlugin();

        /// <summary>
        /// Gets the instent.
        /// </summary>
        /// <value>
        /// The instent.
        /// </value>
        public static DynamicLoadPlugin Instent
        {
            get
            {
                return _DynamicLoadPlugin;
            }
        }

        /// <summary>
        /// Gets the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        internal RulesAnalyzer Get(string name)
        {
            if (plugins.Count > 0)
            {
                if (plugins[name] != null)
                {
                    return plugins[name];
                }
                else
                {
                    Load(name);
                }
            }
            return null;
        }

        /// <summary>
        /// Loads the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        internal void Load(string name)
        {
            if (string.IsNullOrEmpty(name)) return;
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "\\plugins\\" + name;
                Assembly assembly = Assembly.LoadFrom(path);
                Type type = assembly.GetTypes().First(x => x.BaseType == typeof(RulesAnalyzer));
                plugins[name] = (RulesAnalyzer)assembly.CreateInstance(type.FullName);
            }
            catch
            {
                throw;
            }
        }
    }
}
